<template>
  <BasicContainer>
    <FyCurd
      ref="crud"
      v-model="form"
      :page.sync="page"
      :data="tableData"
      :permission="permissionList"
      :table-loading="tableLoading"
      :option="tableOption"
      :before-open="handleOpenBefore"
      @on-load="getList"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @size-change="sizeChange"
      @current-change="currentChange"
      @row-update="handleUpdate"
      @row-save="handleSave"
      @row-del="handleDel">
      <template #menuLeft>
        <ElButton
          v-if="permissions.tender_supervision_export"
          class="filter-item"
          plain
          type="primary"
          size="small"
          icon="el-icon-download"
          @click="exportExcel">
          导出
        </ElButton>
      </template>
      <template #menu="{ type, size, row }">
        <ElButton
          v-if="permissions.tender_supervision_add"
          :type="type"
          :size="size"
          icon="el-icon-edit"
          @click="addBasicSituation(row)">
          基本情况
        </ElButton>
      </template>
      <template #supervisionPersonForm>
        <ElInput
          v-model="form.supervisionPerson"
          :disabled="false"
          placeholder="选择监督人"
          @focus="openSelectUserDialog(1)" />
      </template>
      <template #projectUnitForm="{ disabled }">
        <VueTreeSelect
          v-model="form.projectUnitId"
          :options="functionDeptOption"
          :normalizer="normalizer"
          :disabled="disabled"
          :show-count="true"
          placeholder="选择项目单位"
          @select="functionNameSelect" />
      </template>
      <template #projectLeaderForm>
        <ElInput
          v-model="form.projectLeader"
          :disabled="false"
          placeholder="选择项目负责人"
          @focus="openSelectUserDialog(3)" />
      </template>
      <template #agentForm>
        <ElInput v-model="form.agent" :disabled="false" placeholder="选择经办人" @focus="openSelectUserDialog(4)" />
      </template>
      <template #uploadPageForm>
        <UploadPage
          ref="UploadPage"
          :unique-code="form.unid"
          model="problem"
          :view-type="viewType"
          classify="non_pub_tender" />
      </template>
    </FyCurd>
    <!--excel 模板导入 -->
    <ExcelUpload
      ref="excelUpload"
      title="非公开投标信息导入"
      :url="`${services.personnelService}/tendersupervision/nonPubTenderImport`"
      :temp-url="`${services.personnelService}/sys-file/local/nonPubTender.xlsx`"
      temp-name="非公开投标信息导入模板.xlsx"
      @refreshDataList="refreshChange" />
    <!-- 基本情况弹出框 -->
    <ElementDialog
      :close-on-click-modal="false"
      append-to-body
      :visible.sync="visibleTenderBasic"
      :upload-permissions="permissionList"
      title="基本情况"
      top="5%"
      width="95%">
      <TenderBasic
        v-if="visibleTenderBasic"
        ref="tenderBasic"
        :tender-supervision-id="tenderSupervisionId"
        :tender-type="1" />
      <template #footer>
        <span class="dialog-footer">
          <ElButton @click="visibleTenderBasic = false">关闭</ElButton>
          <!--        <el-button type="primary" @click="checkRowData" >确定</el-button>-->
        </span>
      </template>
    </ElementDialog>
    <UserPicker
      v-if="visibleSelectUser"
      :pre-selected-users="users"
      :reserve-position-on-close="false"
      close-on-click-modal
      :visible.sync="visibleSelectUser"
      @confirm="getUserData" />
  </BasicContainer>
</template>

<script>
  import { fetchList, addObj, putObj, delObj } from '@/api/problem/tendersupervision'
  import { tableOption } from '@/const/crud/problem/non_pub_tender_supervision'
  import { mapState } from 'vuex'

  import TenderBasic from '@/module/problem/tender_basic/index'
  import { services } from '@/config'
  import { fetchTree } from '@/api/admin/dept'
  import { uuid } from '@web-utils/integrations/uuid'

  export default {
    name: 'Tendersupervision',
    components: {
      TenderBasic
    },
    data() {
      return {
        searchForm: {},
        tableData: [],
        users: [],
        functionDeptOption: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption,
        form: {},
        visibleSelectUser: false,
        // 默认只能选择一条用户信息
        chooseUserNum: 1,
        visibleSelectDept: false,
        tenderSupervisionId: -1,
        visibleTenderBasic: false,
        uniqueCode: '',
        services,
        viewType: ''
      }
    },
    computed: {
      ...mapState('user', ['permissions']),
      permissionList() {
        return {
          addBtn: this.$isEmpty(this.permissions.tender_supervision_add, false),
          delBtn: this.$isEmpty(this.permissions.tender_supervision_del, false),
          editBtn: this.$isEmpty(this.permissions.tender_supervision_edit, false),
          downloadBtn: this.$isEmpty(this.permissions.tender_supervision_download, false)
        }
      }
    },
    created() {
      this.init()
    },
    methods: {
      async init() {
        const res = await fetchTree()
        this.functionDeptOption = res.data.data
      },
      // 列表查询
      getList(page, params) {
        // 非公开招标
        this.searchForm.tenderType = 1
        this.tableLoading = true
        fetchList(
          Object.assign(
            {
              current: page.currentPage,
              size: page.pageSize,
              descs: ['create_time']
            },
            params,
            this.searchForm
          )
        )
          .then(response => {
            this.tableData = response.data.data.records
            this.page.total = response.data.data.total
            this.tableLoading = false
          })
          .catch(() => {
            this.tableLoading = false
          })
      },
      // 删除
      handleDel: function (row, index) {
        this.$confirm(`是否确认删除ID为${row.id}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return delObj(row.id)
          })
          .then(data => {
            this.$message.success('删除成功')
            this.getList(this.page)
          })
      },
      // 更新
      handleUpdate: function (row, index, done, loading) {
        putObj(row)
          .then(data => {
            this.$message.success('修改成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 保存
      handleSave: function (row, done, loading) {
        row.tenderType = 1
        addObj(row)
          .then(data => {
            this.$message.success('添加成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 每页条数改变事件
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 当前页发生改变事件
      currentChange(current) {
        this.page.currentPage = current
      },
      // 查询事件
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新事件
      refreshChange() {
        this.getList(this.page)
      },
      //  导出excel
      exportExcel() {
        const exportFileName = `非公开招标监督_${this.$dateFormat(new Date())}.xlsx`
        this.$downBlobCustomeFile(
          `${services.personnelService}tendersupervision/export`,
          this.searchForm,
          this.tableOption.column,
          exportFileName
        )
      },
      // 打开模态框之前
      handleOpenBefore(show, type) {
        window.boxType = type
        this.viewType = type

        // 添加附件参数
        if (type === 'add') {
          const tempUuid = uuid(true)
          this.uniqueCode = tempUuid
          this.form.unid = tempUuid
        } else {
          this.uniqueCode = this.form.unid
        }
        show()
      },
      getUserData(userData) {
        const user = userData[0]
        // 选择一条时
        // 监督人
        if (this.selectUserType === 1) {
          this.form.supervisionPerson = user.name
          this.form.supervisionPersonId = user.id
        } else if (this.selectUserType === 2) {
          // 选择多条时 评标专家
          this.form.participants = userData.map(item => item.name).join(',')
          this.form.participantsId = userData.map(item => item.id).join(',')
        } else if (this.selectUserType === 3) {
          // 项目负责人
          this.form.projectLeader = user.name
          this.form.projectLeaderId = user.id
          this.form.projectUnitId = user.deptId
          this.form.projectUnit = user.deptName
        } else if (this.selectUserType === 4) {
          // 经办人
          this.form.agent = user.name
          this.form.agentId = user.id
        }
      },
      getDetpData(deptData) {
        this.form.projectUnit = deptData[0].name
        this.form.projectUnitId = deptData[0].id
      },
      openSelectUserDialog(type) {
        this.chooseUserNum = 1
        this.selectUserDialog(type)
      },
      openMulSelUserDialog(type) {
        // -1代表任意条
        this.chooseUserNum = -1
        this.selectUserDialog(type)
      },
      selectUserDialog(type) {
        this.selectUserType = type
        this.visibleSelectUser = this.viewType !== 'view'
      },
      openSelectDeptDialog(type) {
        this.selectDeptType = type
        this.visibleSelectDept = true
        this.$nextTick(() => {
          this.$refs.selectDept.init()
        })
      },
      addBasicSituation(row) {
        this.visibleTenderBasic = true
        this.tenderSupervisionId = parseInt(row.id)
      },
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      functionNameSelect(node, instanceId) {
        this.form.projectUnitId = node.id
        this.form.projectUnit = node.name
      }
    }
  }
</script>
